package farmer.update.building;

import pathfinding.grid.GridPath;

import java.util.ArrayList;

import farmer.render.unit.Worker;
import farmer.core.BuildingRessource;

public abstract class Windmill extends BuildingRessource{
	
	public static int woodCostS = 45;
	public static int rockCostS = 15;

	protected ArrayList<Worker> workerList = new ArrayList<Worker>();
	private ArrayList<Worker> workerAtBaseList = new ArrayList<Worker>();
	private final int totalWorker = 2;
	private int maxRessource = 20;
	private int ressourceCollected = 0;

	public Windmill(int x, int y) {
		super(x, y);
		size = 3;
		woodCost = 45;
		rockCost = 15;
	}
	
	public void placeBuilding(){
		for(int i=0; i<totalWorker; i++){
			Worker worker = new Worker(posX+1, posY+2, this);
			workerList.add(worker);
			map.addUnit(worker);
			workerAtBaseList.add(worker);
		}
	}
	
	@Override
	public int getRessource(){
		if(ressource > 5){
			ressource -= 5;
			ressourceCollected -= 5;
			return 5;
		}else{
			int n = ressource;
			ressource = 0;
			ressourceCollected -= n;
			return n;
		}
	}
	
	public void addFreeWorker(Worker worker){
		workerAtBaseList.add(worker);
		ressource++;
	}
	
	public void destroy(){
		for(int i=0; i<workerList.size(); i++){
			map.removeUnit(workerList.get(i));
		}
	}
	
	public void update(int deltaTime){
		if(ressourceCollected < maxRessource){
			for(int i=0; i<workerAtBaseList.size(); i++){
				//Find a tree that is not selected
				//Find the path to that tree
				//Set the path of the unit
				Worker worker = workerAtBaseList.get(i);
				Farm farm = findClosestFarm(worker);
				if(farm != null){
					GridPath path = map.getPath(worker, farm);
					worker.setPath(path);
					farm.setWorkerSelect();
					worker.setFarm(farm);
					workerAtBaseList.remove(i);
					i--;
					ressourceCollected++;
				}
			}
		}
	}
	
	private Farm findClosestFarm(Worker worker){
		int x = worker.getX()/Map.cellWidth;
		int y = worker.getY()/Map.cellWidth;
		Farm farm = map.getClosestFarm(x, y);
		return farm;
	}

}
